#include "input_net_dev.h"



#define SERV_PORT 8000
static int sock_fd;
static int len;
Input_dev Input_net_dev = {
	.name = "input_net_dev" ,
	.bind_dir = net_bind_dir ,
	.init_dev = net_init_dev ,
	.exit_dev = net_exit_dev ,
	.flash_input_data = net_flash_input_data,
	.get_input_data = net_get_input_data,
};

int net_bind_dir(char* name) {
	Input_net_dev.dir_name = name;
	return 0;
}

int net_init_dev() {

	//注意这里分配内存给数据区
	Input_net_dev.idata = (pInput_data)malloc(sizeof(Input_data));
	
	sock_fd = socket(AF_INET, SOCK_DGRAM, 0);
	if(sock_fd < 0)  
	{  
		perror("socket");  
	   	return -1;
	}
    struct sockaddr_in addr_serv;  
    memset(&addr_serv, 0, sizeof(struct sockaddr_in));   //这里用了UDP协议
	addr_serv.sin_family = AF_INET;
	addr_serv.sin_port = htons(SERV_PORT);
	addr_serv.sin_addr.s_addr = htonl(INADDR_ANY); 
	len = sizeof(addr_serv);
    if(bind(sock_fd, (struct sockaddr *)&addr_serv, sizeof(addr_serv)) < 0)  
    {  
    	perror("bind error:");  
    	return -1;
   	}  
	return 0;
	
}

int net_exit_dev() {
	close(sock_fd);
	return 0;
}

void net_flash_input_data() {
	struct sockaddr_in addr_client;  
	int recv_num = recvfrom(sock_fd, Input_net_dev.idata->net_data, 1023, 0, (struct sockaddr *)&addr_client, (socklen_t *)&len);  	 
	if(recv_num < 0)  
	{  
		perror("recvfrom error:");  
		exit(1);  
	}  
	Input_net_dev.idata->net_data[recv_num] = '\0';  
	Input_net_dev.idata->INPUT_TYPE = INPUT_TYPE_NET;
	
}

pInput_data net_get_input_data(void) {
	net_flash_input_data();
	return Input_net_dev.idata;
}






